package main.kotlin.network.client

import java.io.*
import java.net.Socket
import java.nio.charset.StandardCharsets
import java.util.*

class ClientImpl() : Client() {

    private var sock:Socket? = null

    override fun openClient(port: Int) {
        println("client is running...")
        closeClient()

        sock = if (port>=0xFFFF || port<=1024) Socket("localhost", defaultPort) else Socket("localhost", port)

        println("port=$port")
        sock?.apply {
            val input = getInputStream()
            val output = getOutputStream()
            handle(input, output)
        }
        println("disconnected.")
    }

    override fun closeClient() {
        if (sock?.isClosed == false){
            println("closeClient: ")
            sock?.close()
        }
    }

    @Throws(IOException::class)
    private fun handle(input: InputStream, output: OutputStream) {
        val writer = BufferedWriter(OutputStreamWriter(output, StandardCharsets.UTF_8))
        val reader = BufferedReader(InputStreamReader(input, StandardCharsets.UTF_8))
        val scanner = Scanner(System.`in`)
        println("[server] " + reader.readLine())
        while (true) {
            print(">>> ") // 打印提示
            val s: String = scanner.nextLine() // 读取一行输入
            writer.write(s)
            writer.newLine()
            writer.flush()
            val resp = reader.readLine()
            println("[server] $resp")
            if (resp == "bye") {
                break
            }
        }
    }
}